<?php

namespace App\Service\Files;

use App\Service\ServiceGeneral;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Filesystem\FilesystemFactory;

class FilesService extends ServiceGeneral
{
    // TODO 这里以后可以用循环去从OSS或者本地读取文件

    #[Inject]
    public FilesystemFactory $filesystemFactory;

    public function uploadFile($file,$path,$local = 'local'){
        $local = $this->filesystemFactory->get($local);
        $stream = fopen($file->getRealPath(), 'r+');
        $filePath = 'uploads'.DIRECTORY_SEPARATOR.$path;
        $local->writeStream(
            $filePath,
            $stream
        );
        fclose($stream);
        return $filePath;
    }

    /**
     * 文件是否存在 存在 true
     * @param $path
     * @return bool
     * @throws \League\Flysystem\FilesystemException
     */
    public function fileExist($path){
        $local = $this->filesystemFactory->get('local');
        $exists = $local->has($path);
        if($exists){
            return true;
        }
        return false;
    }

    // 读取文件
    public function getLocalFile($path){
        $local = $this->filesystemFactory->get('local');
        return $local->read($path);
    }

}